package com.func.domain.strategy.service.rule.chain.factory;

import com.func.domain.strategy.model.entity.StrategyEntity;
import com.func.domain.strategy.repository.IStrategyRepository;
import com.func.domain.strategy.service.rule.chain.ILogicChain;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @ClassName DefaultLogicChainFactory
 * @Description 责任链工厂
 * @Author: func
 * @Date 2025/2/28 12:46
 * @Version 1.0
 */

@Slf4j
@Service
public class DefaultLogicChainFactory {
    private final Map<String, ILogicChain> logicChainGroup;
    protected IStrategyRepository repository;

    // 构造注入
    public DefaultLogicChainFactory(Map<String, ILogicChain> logicChainGroup, IStrategyRepository repository) {
        this.logicChainGroup = logicChainGroup;
        this.repository = repository;
    }

    public ILogicChain openLogicChain(Long strategyId){
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruleModels = strategyEntity.ruleModels();
        // 如果没有前置规则过滤, 则只装配默认的抽奖
        if (null == ruleModels || 0 == ruleModels.length) {
            return logicChainGroup.get("default");
        }

        ILogicChain logicChain = logicChainGroup.get(ruleModels[0]);
        ILogicChain current = logicChain;
        for (int i = 1; i < ruleModels.length; i++) {
            ILogicChain nextChain = logicChainGroup.get(ruleModels[i]);
            current = current.appendNext(nextChain);
        }
        // 责任链的最后添加上默认责任链
        current.appendNext(logicChainGroup.get("default"));

        return  logicChain;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {
        /**
         * 抽奖奖品ID - 内部流转使用
         */
        private Integer awardId;
        /**
         * 抽奖类型；黑名单抽奖、权重规则、默认抽奖
         */
        private String logicModel;
        /**
         * 抽奖奖品规则
         */
        private String awardRuleValue;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {
        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_WEIGHT("rule_weight", "权重抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        ;


        private final String code;
        private final String info;
    }
}
